package com.jkoss.wine.warehouse.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.UuidUtil;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.merchant.entity.MerchantProductNorm;
import com.jkoss.wine.merchant.service.IMerchantProductNormService;
import com.jkoss.wine.warehouse.entity.WareTransferOrder;
import com.jkoss.wine.warehouse.entity.WareTransferOrderDetails;
import com.jkoss.wine.warehouse.entity.Warehouse;
import com.jkoss.wine.warehouse.service.IWareTransferOrderDetailsService;
import com.jkoss.wine.warehouse.service.IWareTransferOrderService;
import com.jkoss.wine.warehouse.service.IWarehouseService;
import com.jkoss.wine.warehouse.vo.WareTransferOrderVoExcel;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;

/**
 * 仓库调拨单 前端控制器
 * 
 * @Author Jason
 * @Version 1.0, 2018-11-30
 * @See
 * @Since com.jkoss.wine.warehouse.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/warehouse/wareTransferOrder")
public class WareTransferOrderController extends BaseController {

	@Autowired
	private IWareTransferOrderService iWareTransferOrderService;
	@Autowired
	private IWarehouseService iWarehouseService;
	@Autowired
	private IMerchantProductNormService iMerchantProductNormService;
	@Autowired
	private IWareTransferOrderDetailsService iWareTransferOrderDetailsService;

	@RequestMapping("/list")
	@RequiresPermissions("/warehouse/wareTransferOrder/list")
	public String list(String onum, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		dwzPageBean.getCountResultMap().put("onum", onum);
		Wrapper wtoWrapper = Condition.create().ne("wto.del", 1).like("wto.onum", onum);
		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wtoWrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wtoWrapper.orderBy("wto.add_time", false);
		}
		Page resultPage = iWareTransferOrderService.selectVoByPage(dwzPageBean.toPage(), wtoWrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "warehouse/wareTransferOrder/list";
	}

	@RequestMapping("/toInsert")
	@RequiresPermissions("/warehouse/wareTransferOrder/toInsert")
	public String toInsert(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Wrapper whwrapper = Condition.create().ne("del", 1);
		List<Warehouse> warehouses = iWarehouseService.selectList(whwrapper);
		Wrapper mpnwrapper = Condition.create().ne("del", 1);
		map.put("productNorms", iMerchantProductNormService.selectList(mpnwrapper));
		map.put("warehouses", warehouses);
		return "warehouse/wareTransferOrder/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/warehouse/wareTransferOrder/toInsert")
	@ResponseBody
	public Object insert(@Valid WareTransferOrder ware_transfer_order, String iwid[], String owid[], String pnid[], String amut[], String remk[], HttpServletRequest request, HttpServletResponse response) throws Exception {

		if (CommonUtil.isBlank(iwid)) {
			return ajaxError("请选择调入仓库");
		}
		if (CommonUtil.isBlank(owid)) {
			return ajaxError("请选择调出仓库");
		}
		if (CommonUtil.isBlank(pnid)) {
			return ajaxError("请选择商品");
		}
		if (CommonUtil.isBlank(amut)) {
			return ajaxError("请选择数量");
		}

		for (int i = 0; i < iwid.length; i++) {
			if (CommonUtil.isEquals(iwid[i], owid[i])) {
				return ajaxError("调入仓库和调出仓库不能一致");
			}
		}

		// 判断订单编号是否存在
		Wrapper wrapper = Condition.create().ne("del", 1).eq("onum", ware_transfer_order.getOnum());
		WareTransferOrder wareTransferOrder = iWareTransferOrderService.selectOne(wrapper);
		if (!CommonUtil.isBlank(wareTransferOrder) && wareTransferOrder.getDel() != 1) {
			return ajaxError("订单编号已存在");
		}

		// 制单人
		ware_transfer_order.setSgps(getUserId());
		// 添加时间
		ware_transfer_order.setAddTime(CommonUtil.getDate());
		// 操作人
		ware_transfer_order.setOperator(getUserId());
		// 是否删除 0否 1是
		ware_transfer_order.setDel(0);
		// 制单时间
		ware_transfer_order.setOdtm(CommonUtil.getDate());
		if (iWareTransferOrderService.insertTransferOrder(ware_transfer_order, iwid, owid, pnid, amut, remk)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	@RequestMapping("/toUpdate")
	@RequiresPermissions("/warehouse/wareTransferOrder/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		WareTransferOrder wareTransferOrder = iWareTransferOrderService.selectById(id);
		map.put("record", wareTransferOrder);
		Wrapper whwrapper = Condition.create().ne("del", 1);
		List<Warehouse> warehouses = iWarehouseService.selectList(whwrapper);
		Wrapper mpnwrapper = Condition.create().ne("del", 1);
		map.put("productNorms", iMerchantProductNormService.selectList(mpnwrapper));
		map.put("warehouses", warehouses);
		Wrapper wrapper = Condition.create().eq("wood.toid", id).ne("wood.del", 1);
		map.put("orderDetails", iWareTransferOrderDetailsService.selectVoByIoid(wrapper));
		return "warehouse/wareTransferOrder/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/warehouse/wareTransferOrder/toUpdate")
	@ResponseBody
	public Object update(@Valid WareTransferOrder ware_transfer_order, String orderRemk, String wtoodid[], String iwid[], String owid[], String pnid[], String amut[], String remk[], HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (CommonUtil.isBlank(iwid)) {
			return ajaxError("请选择调入仓库");
		}
		if (CommonUtil.isBlank(owid)) {
			return ajaxError("请选择调出仓库");
		}
		if (CommonUtil.isBlank(pnid)) {
			return ajaxError("请选择商品");
		}
		if (CommonUtil.isBlank(amut)) {
			return ajaxError("请选择数量");
		}

		for (int i = 0; i < iwid.length; i++) {
			if (CommonUtil.isEquals(iwid[i], owid[i])) {
				return ajaxError("调入仓库和调出仓库不能一致");
			}
		}
		// 判断订单编号是否存在
		Wrapper wrapper = Condition.create().ne("del", 1).eq("onum", ware_transfer_order.getOnum()).ne("id", ware_transfer_order.getId());
		WareTransferOrder wareTransferOrder = iWareTransferOrderService.selectOne(wrapper);
		if (!CommonUtil.isBlank(wareTransferOrder) && wareTransferOrder.getDel() != 1) {
			return ajaxError("订单编号已存在");
		}
		ware_transfer_order.setRemk(orderRemk);
		if (iWareTransferOrderService.updateTransferOrder(ware_transfer_order, wtoodid, iwid, owid, pnid, amut, remk)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/delete")
	@RequiresPermissions("/warehouse/wareTransferOrder/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<WareTransferOrder> list = new ArrayList();
		for (String string : id) {
			WareTransferOrder transferOrder = new WareTransferOrder();
			transferOrder.setId(string);
			// 是否删除：0-未删除、1-已删除、2-不能删除
			transferOrder.setDel(1);
			list.add(transferOrder);
		}
		if (iWareTransferOrderService.deleteTransferOrder(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 订单详情
	 * 
	 * @param dwzPageBean
	 * @param wname
	 * @param ioid
	 * @param map
	 * @param str
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/details")
	@RequiresPermissions("/warehouse/wareTransferOrder/details")
	public String details(DwzPageBean dwzPageBean, String wname, String toid, ModelMap map, String str, HttpServletRequest request, HttpServletResponse response) {
		map.put("str", str);
		map.put("toid", toid);
		map.put("details", iWareTransferOrderService.selectVoById(toid));
		Wrapper wrapper = Condition.create().eq("wtod.toid", toid).ne("wtod.del", 1);
		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("wtod.add_time", false);
		}
		Page resultPage = iWareTransferOrderDetailsService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "warehouse/wareTransferOrder/details";
	}

	/**
	 * 导出EXCEL
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/export")
	@RequiresPermissions("/warehouse/wareTransferOrder/export")
	public String export(ModelMap map, DwzPageBean dwzPageBean, HttpServletRequest request, HttpServletResponse response) {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().ne("wto.del", 1);
		// 根据用户id获取角色
		// boolean isDirector = true;
		// List<Role> roles = getRoleList();
		// for (Role role : roles) {
		// if ("运营主管".equals(role.getName())) {
		// isDirector = false;
		// }
		// }
		// if (isDirector) {
		// wrapper.eq("maid", getUserId());
		// }
		Page page = dwzPageBean.toPage();
		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		List list = iWareTransferOrderService.selectVoExcel(page, wrapper).getRecords();
		ExportParams params = new ExportParams(null, "仓库调拨单", ExcelType.XSSF);
		// IExcelDataHandler dataHandler = new MoneyExcelHandler();
		// dataHandler.setNeedHandlerFields(new String[] { "订单金额" });
		// params.setDataHandler(dataHandler);
		map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
		map.put(NormalExcelConstants.CLASS, WareTransferOrderVoExcel.class);// 导出实体
		map.put(NormalExcelConstants.PARAMS, params);// 参数
		map.put(NormalExcelConstants.FILE_NAME, "仓库调拨单");// 文件名称
		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;// View名称
	}

	/**
	 * 去导入页面
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toImportExcel")
	@RequiresPermissions("/warehouse/wareTransferOrder/toImportExcel")
	public String toImportExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		return "/warehouse/wareTransferOrder/importExcel";
	}

	/**
	 * 导入EXCEL
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/importExcel")
	@RequiresPermissions("/warehouse/wareTransferOrder/toImportExcel")
	@ResponseBody
	public Object importExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 1.构造导入参数
		ImportParams params = new ImportParams();
		// 指定title位置
		// 2.importExcelMore解释Excel
		ExcelImportResult<WareTransferOrderVoExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), WareTransferOrderVoExcel.class, params);
		// 3.插入数据库
		List<WareTransferOrderVoExcel> wareTransferOrderVoExcels = result.getList();
		if (!CommonUtil.isBlank(wareTransferOrderVoExcels)) {
			// 为提高效率一次查询所有用户，放到map当中
			Map<String, String> whmap = new HashMap();
			List<Warehouse> warehouses = iWarehouseService.selectList(null);
			if (!CommonUtil.isBlank(warehouses)) {
				for (Warehouse warehouse : warehouses) {
					whmap.put(warehouse.getName(), warehouse.getId());
				}
			}
			// 为提高效率一次查询所有用户，放到map当中
			Map<String, String> mpnmap = new HashMap();
			Wrapper mpnWrapper = Condition.create().ne("del", 1);
			List<MerchantProductNorm> merchantProductNorms = iMerchantProductNormService.selectList(mpnWrapper);
			if (!CommonUtil.isBlank(merchantProductNorms)) {
				for (MerchantProductNorm merchantProductNorm : merchantProductNorms) {
					mpnmap.put(merchantProductNorm.getNormName(), merchantProductNorm.getMerchantProductNormId());
				}
			}

			List<WareTransferOrder> orders = new ArrayList();
			List<WareTransferOrderDetails> orderDetails = new ArrayList();
			Map map = new HashMap();

			for (WareTransferOrderVoExcel excel : wareTransferOrderVoExcels) {
				// 把wareInOrderExcel转换成WareInOrder
				WareTransferOrder order = CommonUtil.cloneJavaBean(excel, WareTransferOrder.class);
				if (CommonUtil.isBlank(map.get(order.getOnum()))) {
					map.put(order.getOnum(), order.getOnum());
					order.setId(UuidUtil.getUUID());
					// 制单人
					order.setSgps(getUserId());
					// 操作人
					order.setOperator(getUserId());
					// 添加时间
					order.setAddTime(CommonUtil.getDate());
					// 是否删除：0-未删除、1-已删除、2-不能删除
					order.setDel(0);
					orders.add(order);
				}
				WareTransferOrderDetails newOrderDetails = new WareTransferOrderDetails();
				// 操作人
				newOrderDetails.setOperator(getUserId());
				// 添加时间
				newOrderDetails.setAddTime(CommonUtil.getDate());
				// 是否删除：0-未删除、1-已删除、2-不能删除
				newOrderDetails.setDel(0);

				newOrderDetails.setAmut(excel.getAmut());
				newOrderDetails.setIwid(whmap.get(excel.getInname()));
				newOrderDetails.setOwid(whmap.get(excel.getOutname()));
				newOrderDetails.setPnid(mpnmap.get(excel.getPnname()));
				newOrderDetails.setRemk(excel.getDremk());
				newOrderDetails.setToid(order.getId());

				orderDetails.add(newOrderDetails);
			}
			if (!iWareTransferOrderService.insertBatch(orders)) {
				return ajaxError("添加数据失败！");
			}
			if (!iWareTransferOrderDetailsService.insertBatch(orderDetails)) {
				return ajaxError("添加数据失败！");
			}
		} else {
			return ajaxError("数据内容为空！");
		}
		return ajaxSuccess();
	}
}
